import {Component, HostBinding, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {AuthService} from '../auth/auth.service';
import {loginTransition} from './login.animation';
import {SystemUtils} from "../commons/system.utils";
import {ConfirmationService} from "_primeng@11.3.2@primeng/api";
import {TranslateService} from '@ngx-translate/core';
import {AccountData} from "../account/account.data";
import {globalCache} from "../commons/cache.manage";

/**
 * 登陆页组件
 * @author 王锦阳
 * @version 1.0
 * @since 2018/09/19
 */
@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss'],
    animations: [ loginTransition ]
})
export class LoginComponent implements OnInit {

    @HostBinding('@loginTransition') state = 'activated';
    public displayRegisterModal: boolean = false;
    public year: number = 0;
    public loginForm: FormGroup;
    public registerForm: FormGroup;
    public disableSendBtn: boolean;
    private captchaKey: string = '';

    constructor(
        private loginService: AuthService,
        private formBuilder: FormBuilder,
        private confirmationService: ConfirmationService,
        private translate: TranslateService) {
        this.year = new Date().getFullYear();
    }

    ngOnInit() {
        this.loginService.getSystemInfo().then(resp => {
            if (!resp.success) {
                this.confirmationService.confirm({
                    key: 'error',
                    message: this.translate.instant('auth.login.system.error'),
                    header: this.translate.instant('commons.error'),
                    acceptLabel: this.translate.instant('commons.ok'),
                    icon: 'pi pi-exclamation-triangle',
                    rejectVisible: false
                });
                return;
            }
            globalCache.setSystem("_CACHE_SYSTEM_BASE_", resp.data);
            this.loginService.checkToken();
        });
        this.initLoginForm();
        this.initRegisterForm();
    }

    private initLoginForm() {
        this.loginForm = this.formBuilder.group({
            'name': new FormControl('', Validators.required),
            'password': new FormControl('',
                Validators.compose([
                    Validators.required,
                    Validators.minLength(6),
                    Validators.maxLength(32)
                ])
            )
        });
        this.loginService.getYear().then(data => {
            this.year = data;
        }).catch(reason => {
            console.warn("版权信息请求失败，错误原因：" + reason);
        });
    }

    private initRegisterForm() {
        const pwdValidator = () => {
            if (!this.registerForm) {
                return null;
            }
            const pwd: string = this.registerForm.controls['loginPassword'].value;
            const confirmPwd: string = this.registerForm.controls['surePassword'].value;
            if (pwd !== confirmPwd || pwd === '' || confirmPwd === '') {
                return {no_match: true};
            }
            return null;
        };

        this.registerForm = this.formBuilder.group({
            'loginName': new FormControl('', Validators.required),
            "loginPassword": new FormControl('', [
                Validators.required,
                Validators.minLength(6),
                Validators.maxLength(32)
            ]),
            "surePassword": new FormControl('', [
                Validators.required,
                Validators.minLength(6),
                Validators.maxLength(32),
                pwdValidator
            ]),
            "email": new FormControl('', Validators.email),
            "userName": new FormControl('', Validators.required),
            "captcha": new FormControl('', [
                Validators.required,
                Validators.minLength(6),
                Validators.maxLength(6)
            ]),
        });
    }

    public disableSendCode() {
        if (this.disableSendBtn) {
            return true;
        }
        const email: FormControl = <FormControl>this.registerForm.get('email');
        return !(SystemUtils.isNotBlank(email.value) && email.valid);
    }

    public showRegisterDialog() {
        this.displayRegisterModal = true;
    }

    public doLoginSubmit(value: object) {
        this.loginService.doLogin(value['name'], value['password']);
    }

    public doSendCode(event) {
        if (this.disableSendCode()) {
            return;
        }
        const email: string = this.registerForm.get('email').value;
        this.loginService.doSendEmailCode(email, key => {
            this.captchaKey = key;
            this.disableSendBtn = true;
            let sec: number = 60;
            const val: string = event.target.textContent;
            const id: number = setInterval(() => {
                event.target.textContent = `(${sec--})`;
                if (sec === 0) {
                    event.target.textContent = val;
                    this.disableSendBtn = false;
                    clearInterval(id);
                }
            }, 1000);
        });
    }

    public doRegisterSubmit(value: AccountData) {
        if (this.captchaKey === '') {
            this.confirmationService.confirm({
                key: 'alert',
                message: this.translate.instant('login.register.captcha.key.empty'),
                header: this.translate.instant('commons.error'),
                acceptLabel: this.translate.instant('commons.ok'),
                icon: 'pi pi-exclamation-triangle',
                rejectVisible: false
            });
            return;
        }
        value.captchaKey = this.captchaKey;
        this.loginService.doRegister(value, () => {
            this.confirmationService.confirm({
                key: 'alert',
                message: this.translate.instant('login.register.success'),
                header: this.translate.instant('commons.warn'),
                acceptLabel: this.translate.instant('commons.ok'),
                icon: 'pi pi-exclamation-triangle',
                rejectVisible: false,
                accept: () => {
                    this.registerForm.reset();
                    this.displayRegisterModal = false;
                    this.captchaKey = '';
                }
            });
        });
    }

}
